package com.house.controller;


import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.house.common.Result;
import com.house.dict.AbstractDictDataImpl;
import com.house.entity.Dict;
import com.house.service.DictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 字典管理
 */
@Controller
@RequestMapping("dict")
public class DictController {

    @Autowired
    DictService dictService;


    /**
     * 通过code查询字典
     * @param code
     * @return
     */
    @PostMapping("/findByCode/{code}")
    @ResponseBody
    public List<Dict> findByCode(@PathVariable("code") String code){
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("code", code);
        wrapper.eq("status", "1");
        wrapper.orderByAsc("sort");
        return dictService.list(wrapper);
    }


    /**
     * 查询所有字典
     * @return
     */
    @PostMapping("/findAllDict")
    @ResponseBody
    public Result findAllDict(){
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("status", "1");
        List<Dict> dicts = dictService.list(wrapper);

        Map<String, List<Dict>> map = new HashMap<>();
        dicts.forEach(dict -> {
            if(map.containsKey(dict.getCode())) {
                map.get(dict.getCode()).add(dict);
            } else {
                List<Dict> list = new ArrayList<>();
                list.add(dict);
                map.put(dict.getCode(), list);
            }
        });


        return Result.ok(map);
    }


    /**
     * 获取业务数据字典
     * @return
     */
    @PostMapping("/findDataDict/{code}")
    @ResponseBody
    public List<Dict> findDataDict(@PathVariable("code") String code){

        // 通过 code 自动获取 bean,  StringUtils.capitalize(code) 将首字母转成大写
        AbstractDictDataImpl bean = SpringUtil.getBean(String.format("dict%sImpl", StringUtils.capitalize(code)));
        List<Dict> dices = bean.execute();
        return dices;
    }



}
